package com.eunion.web.cms.entity.spec;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import com.eunion.web.cms.entity.MajorType;

public final class MajorTypeSpec {

    public static Specification<MajorType> build(MajorType queryBean) {
        return new MajorTypeQuery(queryBean);
    }

    private static class MajorTypeQuery implements Specification<MajorType> {

        private MajorType queryBean;

        private MajorTypeQuery(MajorType queryBean) {
            this.queryBean = queryBean;
        }

        @Override
        public Predicate toPredicate(Root<MajorType> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> list = getPredicates(root, query, cb, queryBean);
            Predicate[] preList = new Predicate[list.size()];
            return cb.and(list.toArray(preList));
        }

    }

    private static List<Predicate> getPredicates(Root<MajorType> root, CriteriaQuery<?> query, CriteriaBuilder cb,
        MajorType queryBean) {
        // 条件集合
        List<Predicate> list = new ArrayList<>();

        // 专业类型代码条件
        String majorTypeCode = queryBean.getMajorTypeCode();
        if (StringUtils.isNotBlank(majorTypeCode)) {
            list.add(cb.like(root.get("majorTypeCode"), "%" + majorTypeCode.trim() + "%"));
        }

        // 专业类型名称条件
        String majorTypeName = queryBean.getMajorTypeName();
        if (StringUtils.isNotBlank(majorTypeName)) {
            list.add(cb.like(root.get("majorTypeName"), "%" + majorTypeName.trim() + "%"));
        }

        // 上级类型代码条件
        String parentCode = queryBean.getParentCode();
        if (StringUtils.isNotBlank(parentCode)) {
            list.add(cb.equal(root.get("parentCode"), parentCode.trim()));
        }

        return list;
    }
}
